#include "resource_request_context.h"
#include "base/string_util.h"
#include "base/threading/worker_pool.h"
#include "net/proxy/proxy_service.h"
#include "net/base/ssl_config_service_defaults.h"
#include "net/http/http_network_layer.h"
#include "net/url_request/static_http_user_agent_settings.h"
#include "net/url_request/url_request_job_factory_impl.h"
#include "net/http/http_server_properties_impl.h"

namespace dl {
using namespace net;

// 创建默认的HostResolver
scoped_ptr<HostResolver> CreateSystemHostResolver(NetLog* net_log) {
	HostResolver::Options options;
	options.max_concurrent_resolves = 10;
	options.max_retry_attempts = 3;
	scoped_ptr<HostResolver> resolver = 
		HostResolver::CreateSystemResolver(options, net_log);
	return resolver.PassAs<HostResolver>();
}

// ResourceRequestContext
ResourceRequestContext::ResourceRequestContext()
    : ALLOW_THIS_IN_INITIALIZER_LIST(context_storage_(this)){
  Init();
}

ResourceRequestContext::~ResourceRequestContext() {

}

void ResourceRequestContext::Init() {
	if (!host_resolver())
		context_storage_.set_host_resolver(CreateSystemHostResolver(NULL));

	if (!proxy_service())
		context_storage_.set_proxy_service(ProxyService::CreateDirect());

	if (!ssl_config_service())
		context_storage_.set_ssl_config_service(new SSLConfigServiceDefaults);

	if (!http_server_properties()) {
		context_storage_.set_http_server_properties(new HttpServerPropertiesImpl);
	}

	HttpNetworkSession::Params params;
	params.host_resolver = host_resolver();
	params.network_delegate = network_delegate();
	params.cert_verifier = cert_verifier();
	params.proxy_service = proxy_service();
	params.ssl_config_service = ssl_config_service();
	params.http_auth_handler_factory = http_auth_handler_factory();
	params.http_server_properties = http_server_properties();
	params.net_log = net_log();

	if (!http_transaction_factory()) {
		//context_storage_.set_http_transaction_factory(
		//    new HttpCache(new HttpNetworkSession(params), HttpCache::DefaultBackend::InMemory(0)));
		context_storage_.set_http_transaction_factory(
			new HttpNetworkLayer(new HttpNetworkSession(params)));
	}

	if (!http_user_agent_settings()) {
		context_storage_.set_http_user_agent_settings(
			new StaticHttpUserAgentSettings("en-us,fr", "iso-8859-1,*,utf-8", EmptyString()));
	}

	if (!job_factory())
		context_storage_.set_job_factory(new URLRequestJobFactoryImpl);
}

}
